package com.dwusoft.license;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

/**

 * 对文件的删除、剪切、移动和创建文件夹操作

 * 

 * @author Hou Dayu

 */
public class FileOperate {

	private static Logger log = Logger.getLogger(FileOperate.class);
	private static FileOperate instance = null;

	private FileOperate() {

	}

	public synchronized static FileOperate getInstance() {
		if (null == instance)
			instance = new FileOperate();
		return instance;
	}

	/**

	 * 检查文件或文件夹是否存在

	 * 

	 * @param folderPath  文件或文件夹路径

	 * @return            true为存在，false不存在

	 */
	public boolean checkFolder(String folderPath) {
		boolean result = false;
		if (!isNull(folderPath)) {
			File newFilePath = new File(folderPath);
			result = newFilePath.exists();
		}
		return result;
	}

	/**

	 * 新建目录操作

	 * 

	 * @param folderPath 文件夹路径

	 */
	public boolean newCreateFolder(String folderPath) {
		boolean result = false;
		try {
			if (!isNull(folderPath)) {
				File newFilePath = new File(folderPath);
				if (!newFilePath.exists()) {
					result = newFilePath.mkdirs();
				}
			}
		} catch (Exception e) {
			log.error("新建目录操作出错ERROR KEY:" + e.getMessage());
		}
		return result;
	}

	/**

	 * 创建新的文件

	 * 

	 * @param filePathAndName 文件名称

	 * @param fileContent     文件内容

	 */
	public boolean newCreateFile(String filePathAndName, String fileContent) {
		boolean result = false;
		try {
			if (!isNull(filePathAndName)) {
				File newFilePath = new File(filePathAndName);
				if (!newFilePath.exists()) {
					newFilePath.createNewFile();
				}
				FileWriter resultFile = new FileWriter(newFilePath);
				PrintWriter newFile = new PrintWriter(resultFile);
				newFile.println(fileContent);
				resultFile.close();
				newFile.close();
				result = true;
			}
		} catch (Exception e) {
			log.error("新建文件操作出错ERROR KEY:" + e.getMessage());
		}
		return result;
	}

	/**

	 * 创建新的文件

	 * 

	 * @param inputStream 文件内容流

	 * @param filePath    文件路径

	 * @return            返回true为创建成功，false为创建失败

	 */
	public boolean newCreateFile(InputStream inputStream, String filePath) {
		boolean result = false;
		if (inputStream == null)
			return false;
		FileOutputStream output = null;
		try {
			if (checkFolder(filePath))
				delFile(filePath);
			output = new FileOutputStream(filePath);
			byte[] buffer = new byte[1024];
			int bytesRead = 0;
			while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
				output.write(buffer, 0, bytesRead);
			}
			result = true;
		} catch (FileNotFoundException e) {
			log.error("新建文件操作出错ERROR KEY:" + e.getMessage());
		} catch (IOException e) {
			log.error("新建文件操作出错ERROR KEY:" + e.getMessage());
		} finally {
			try {
				if (output != null) {
					output.flush();
					output.close();
				}
				inputStream.close();
			} catch (Exception e) {
				log.error("关闭文件流出错ERROR KEY:" + e.getMessage());
			}
		}
		return result;
	}

	/**

	 * 删除文件

	 * 

	 * @param filePathAndName 文件路径名称

	 * @return                true删除成功，false删除失败

	 */
	public boolean delFile(String filePathAndName) {
		boolean result = false;
		try {
			if (!isNull(filePathAndName)) {
				if (checkFolder(filePathAndName)) {
					File delFile = new File(filePathAndName);
					result = delFile.delete();
				}
				result = true;
			}
		} catch (Exception e) {
			log.error("删除文件操作出错ERROR KEY:" + e.getMessage());
		}
		return result;
	}

	/**

	 * 取目录文件个数

	 * 

	 * @param f 文件目录

	 * @return  返回指定目录中文件的个数

	 */
	public long getlist(File f) {
		long size = 0;
		File flist[] = f.listFiles();
		size = flist.length;
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size--;
			}
		}
		return size;
	}

	/**

	  * description: 获取指定文件夹下的文件列表

	  * @param filePath 文件夹路径

	  * @return

	 */
	public File[] getFileList(String filePath) {
		File file = new File(filePath);
		File flist[] = file.listFiles();
		return flist;
	}

	/**

	 * 修改Property文件

	 * 

	 * @param pathName     文件全路径

	 * @param taskId       主任务ID

	 * @param resourcePath 要写入的值

	 * @param isfalg       true为新增内容，false为清楚内容

	 * @param key          property的KEY的名称

	 */
	public void removePropertyContent(String pathName, String taskId, String resourcePath, boolean isfalg, String key) {
		String result = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(pathName), "utf8"));
			while (br.ready()) {
				String str = br.readLine();
				if (isfalg)
					result += str + "\n";
				else {//清除无用的参数

					if (str.indexOf(taskId) == -1)
						result += str + "\n";
				}
			}
			br.close();
			if (isfalg)
				result += key + "=" + resourcePath;
			newCreateFile(pathName, result);
		} catch (Exception e) {
			log.error("property文件夹操作出错ERROR KEY:" + e.getMessage());
		}
	}

	/**

	 * 修改文件名称

	 * 

	 * @param filePath   文件件全路径

	 * @param namePrefix 新名前缀

	 * @param flag       true为添加对应的名称前缀,false为去掉对应的名称前缀

	 * @return           true为名称修改成功，false为名称修改失败

	 */
	public boolean reFileName(String filePath, String namePrefix, boolean flag) {
		boolean mark = false;
		if (!isNull(filePath) && !isNull(namePrefix)) {
			File file = new File(filePath);
			if (file.isFile()) {
				String fileName = file.getName();
				String path = file.getPath();
				path = path.replace(fileName, "");
				if (flag) {
					fileName = namePrefix + "_" + fileName;
				} else {
					fileName = fileName.replace(namePrefix + "_", "");
				}
				mark = file.renameTo(new File(path + fileName)); //改名  

			}
		}
		return mark;
	}

	/**

	 * 返回文件名

	 *

	 * @param fileName

	 * @return

	 */
	public String getFileName(String fileName) {
		File file = new File(fileName);
		return file.getName();
	}

	/**

	 * 格式化文件路径

	 *

	 * @param path 文件路径

	 * @return

	 */
	public String formatFilePath(String path) {
		if (isNull(path))
			return "";
		path = path.replace("\\", "/");
		path = path.replace("\\\\", "/");
		return path.replace("//", "/");
	}

	private boolean isNull(String text) {
		if ("".equals(text) || "null".equalsIgnoreCase(text) || null == text)
			return true;
		else
			return false;
	}
}